package com.xindaoapp.happypet.ui;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.util.Pair;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter;
import com.xindaoapp.happypet.bean.MyInformMessage;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.TimeFormat;
import com.xindaoapp.happypet.view.CircleImageView;

/**
 * 系统通知列表
 * 
 * @author Stone
 * 
 */
public class MySystemInfoListActivity extends BaseActivity {

    private PullToRefreshListView mPullToRefreshListView;
    private InformMessageAdapter mAdapter;
    private Map<Integer, MyInformMessage> mMap;
    private RelativeLayout mNoData;


    @SuppressLint("UseSparseArrays")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMap = new HashMap<Integer, MyInformMessage>();
    }



    @Override
    protected int getContentViewResId() {
        return R.layout.activity_my_system_info_list;
    }


    @Override
    protected void initViews() {

        mNoData = (RelativeLayout) this.findViewById(R.id.no_data);
        mPullToRefreshListView = (PullToRefreshListView) this.findViewById(R.id.listview);
        mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                onLoadDatas();
            }
        });
        super.initViews();
    }



    protected void handleOnClick(MyInformMessage info) {

        String type = info.getSystype();

        int flg = -1;
        if (type.equals("thread")) {
            flg = 0;
        } else if (type.equals("user")) {
            flg = 1;
        } else if (type.equals("shaitu")) {
            flg = 2;
        }

        int typeId = Integer.parseInt(info.getSystypeid());

        switch (flg) {
            case 0:
                // 进入帖子详情
                Intent intent = new Intent(this, PostDetailActivity.class);
                intent.putExtra(Constants.KEY_POST_TID, info.systypeid);
                startActivity(intent);

                break;
            case 1:
                if (typeId > 0) {
                    // 进入他人中心
                    Intent intent2 = new Intent(this, MyUserCenterActivity.class);
                    intent2.putExtra(Constants.KEY_UID, info.systypeid);
                    intent2.putExtra(Constants.KEY_USERNAME, info.author);
                    intent2.putExtra(Constants.KEY_USERFACE, info.userface);
                    startActivity(intent2);
                }
                break;
            case 2:

                // 进入他人中心
                Intent intent3 = new Intent(this, SplashPictureActivity2.class);
                intent3.putExtra("actID", info.systypeid);
                startActivity(intent3);

                break;

            default:
                break;
        }

    }


    @Override
    protected void initEvents() {
        super.initEvents();
    }


    @Override
    protected void onLoadDatas() {
        super.onLoadDatas();


        getData();



    }


    private void getData() {
        // TODO Auto-generated method stub
        getMoccaApi().getMyInformMessageList(UserState.getUserUid(), Constants.PAGE_FIRST,
                Constants.PAGE_SIZE, new IRequest<List<MyInformMessage>>() {

                    @Override
                    public void request(List<MyInformMessage> t) {



                        if (t != null) {
                            if (t.size() == 0) {
                                Toast.makeText(getApplicationContext(), "暂时还没有系统消息!",
                                        Toast.LENGTH_SHORT).show();
                                mNoData.setVisibility(View.VISIBLE);
                            } else {
                                onDataArrived(true);

                                mNoData.setVisibility(View.GONE);
                                mAdapter =
                                        new InformMessageAdapter(MySystemInfoListActivity.this, t,
                                                Constants.PAGE_SIZE, R.layout.item_system_inform,
                                                R.layout.item_loading);
                                mPullToRefreshListView.getRefreshableView().setAdapter(mAdapter);
                            }

                        } else {
                            onDataArrived(false);
                        }

                        mPullToRefreshListView.onRefreshComplete();


                        // if (null == mAdapter) {
                        // onDataArrived(true);
                        // mAdapter =
                        // new InformMessageAdapter(MySystemInfoListActivity.this, t,
                        // Constants.PAGE_SIZE, R.layout.item_system_inform,
                        // R.layout.item_loading);
                        // mPullToRefreshListView.setAdapter(mAdapter);
                        // } else {
                        // mAdapter.setInitData(t);
                        // mAdapter.notifyDataSetChanged();
                        // }
                        //


                    }

                });
    }



    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                finish();
            }
        };
    }


    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }


    @Override
    protected String getTopBarTitleStrRes() {
        return "系统通知";
    }



    /**
     * 通知
     * 
     * @author xindaoapp
     */
    class InformMessageAdapter extends XinDaoBaseAdapter<MyInformMessage> {

        int pos;

        public InformMessageAdapter(Context context, List<MyInformMessage> iniData, int pageSize,
                int res, int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        public void nextPage(int start, int size,
                final ILoadNextPageData<MyInformMessage> iLoadNextPageData) {

            getMoccaApi().getMyInformMessageList(UserState.getUserUid(), start, size,
                    new IRequest<List<MyInformMessage>>() {

                        @Override
                        public void request(List<MyInformMessage> t) {
                            iLoadNextPageData.loadNextPageData(t);
                        }
                    });
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent,
                final MyInformMessage value) {

            pos = position;

            mMap.put(position, value);

            ViewHolder holder = (ViewHolder) convertView.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.icon = (CircleImageView) convertView.findViewById(R.id.icon);
                holder.time = (TextView) convertView.findViewById(R.id.time);
                holder.content = (TextView) convertView.findViewById(R.id.content);
                convertView.setTag(holder);
            }


            ImageLoader.getInstance().displayImage(value.userface, holder.icon);


            holder.time.setText(TimeFormat.format(CommonUtil
                    .formatTime2Date(value.dateline * 1000l).toString()));

            if ((!value.systype.equals("thread") && !value.systype.equals("user") && !value.systype
                    .equals("shaitu")) || Integer.parseInt(value.systypeid.trim()) <= 0) {
                holder.content.setText(CommonUtil.convetToHtml(CommonUtil.parseEmoji(value.note),
                        mContext));



                // convertView.setOnClickListener(new OnClickListener() {
                //
                // @Override
                // public void onClick(View arg0) {
                // handleOnClick(value);
                // }
                // });
            } else {
                addLink(value, position, holder.content);
            }



            convertView.setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    new AlertDialog.Builder(mContext).setTitle("系统通知").setMessage("确认删除？")
                            .setNegativeButton("取消", null)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                    delete(position, value.id);
                                }
                            }).create().show();
                    return false;
                }
            });

            // item 点击事件
            // convertView.setOnClickListener(new OnClickListener() {
            //
            // @Override
            // public void onClick(View arg0) {
            // handleOnClick(value);
            // }
            // });

            return convertView;
        }

        class ViewHolder {
            CircleImageView icon;
            TextView time;
            TextView content;
        }

        private class MyURLSpan extends ClickableSpan {

            private final String mUrl;

            // private final boolean isClick = false;
            // private TextPaint ds;

            // @Override
            // public void updateDrawState(TextPaint ds) {
            //
            // if (isClick) {
            // ds.setColor(Color.RED);
            // } else {
            // this.ds = ds;
            // ds.setColor(Color.BLUE);
            // }
            // ds.setUnderlineText(true);
            // }

            MyURLSpan(String url) {
                mUrl = url;
            }

            @Override
            public void onClick(View widget) {
                // isClick = true;
                // updateDrawState(ds);
                int flg = Integer.parseInt(mUrl);
                handleOnClick(mMap.get(flg));
            }
        }

        private void addLink(MyInformMessage value, int position, TextView content) {

            int cont1 = value.note.indexOf(" ");
            String countString = "";
            String countString2 = "";

            if (cont1 != -1) {
                countString = value.note.substring(0, cont1);
                countString2 = value.note.substring(cont1);
            } else {
                countString = value.note;
            }

            String replString = "<a href=\"" + position + "" + "\">" + countString + "</a>";
            String resultString = "";

            resultString = replString + " " + countString2;

            content.setText(Html.fromHtml(resultString));

            content.setMovementMethod(LinkMovementMethod.getInstance());
            CharSequence text = content.getText();
            if (text instanceof Spannable) {
                int end = text.length();
                Spannable sp = (Spannable) content.getText();
                URLSpan[] urls = sp.getSpans(0, end, URLSpan.class);
                SpannableStringBuilder style = new SpannableStringBuilder(text);
                style.clearSpans(); // should clear old spans
                for (URLSpan url : urls) {
                    MyURLSpan myURLSpan = new MyURLSpan(url.getURL());
                    style.setSpan(myURLSpan, sp.getSpanStart(url), sp.getSpanEnd(url),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    //
                    // 设置字体（依次包括字体名称，字体大小，字体样式，字体颜色，链接颜色）
                    /*
                     * ColorStateList csllink = null; ColorStateList csl = null; XmlResourceParser
                     * xppcolor = getResources().getXml(R.color.linkcolor); try { csl =
                     * ColorStateList.createFromXml(getResources(), xppcolor); } catch
                     * (XmlPullParserException e) { // TODO: handle exception e.printStackTrace(); }
                     * catch (IOException e) { // TODO: handle exception e.printStackTrace(); }
                     * 
                     * XmlResourceParser xpplinkcolor = getResources().getXml(R.color.linkcolor);
                     * try { csllink = ColorStateList.createFromXml(getResources(), xpplinkcolor); }
                     * catch (XmlPullParserException e) { // TODO: handle exception
                     * e.printStackTrace(); } catch (IOException e) { // TODO: handle exception
                     * e.printStackTrace(); } style.setSpan(new TextAppearanceSpan("monospace",
                     * android.graphics.Typeface.BOLD_ITALIC, 18, csl, csllink), 0, end,
                     * Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                     */
                    //
                }
                content.setText(style);
            }
        }

    }



    private void delete(final int position, String noticeId) {
        getMoccaApi().deleteInformMessage(noticeId, new IRequest<Pair<Boolean, String>>() {

            @Override
            public void request(Pair<Boolean, String> t) {
                if (null != t) {
                    if (t.first) {
                        mAdapter.getResult().remove(position);
                        mAdapter.notifyDataSetChanged();
                    }
                    Toast.makeText(MySystemInfoListActivity.this, t.second, Toast.LENGTH_SHORT)
                            .show();
                } else {
                    Toast.makeText(MySystemInfoListActivity.this, R.string.net_error,
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (mMap.size() != 0) {
            mMap.clear();
            mMap = null;
        }
    }

}
